package com.smartmail.utility;

import java.security.MessageDigest;
import java.util.Date;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import android.util.Log;

/**
 * Class containing methods to compute 'MessageHash' field.
 * It is MD5 hash sum than uniquely identifies every message.
 * 
 * @author Tomek
 *
 */
public class MessageUtility {
	

	private static String convertToHex(byte[] data) {
		
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

	/**
	 * Get MD5 hash sum from given String.
	 * 
	 * @param text - text to compute MD5 hash
	 * @return - MD5 hash sum from given String
	 */
	public static String getMD5Hash(String text)  {
		
		try{
			MessageDigest md;
			md = MessageDigest.getInstance("MD5");
			byte[] md5hash = new byte[32];
			md.update(text.getBytes("US-ASCII"), 0, text.length());
			md5hash = md.digest();
			return convertToHex(md5hash);
		} catch( Exception e){
			
			Log.d(_logTag, "MessageUtility : getMD5Hash");
			return null;
		}
	}
	
	/**
	 * Compute MessageHash field from given MimeMessage object.
	 * 
	 * @param mimeMessage - mimeMessage to compute hash
	 * @return - MessageHash field of given message
	 * @throws MessagingException
	 */
	public static String getHash(MimeMessage mimeMessage) throws MessagingException{
		
		StringBuilder stringToHash = new StringBuilder();
		
		String messageID = mimeMessage.getMessageID();
		if( messageID != null)
			stringToHash.append(messageID);
		
		Date sentDate = mimeMessage.getSentDate();
		if( sentDate != null)
			stringToHash.append(mimeMessage.getSentDate().toString());
		
		if( mimeMessage.getFrom().length > 0 && mimeMessage.getFrom()[0] != null)
			stringToHash.append(mimeMessage.getFrom()[0].toString());
		
		String topic = mimeMessage.getSubject();
		if( topic != null)
			stringToHash.append(topic);
		
		return getMD5Hash(stringToHash.toString());
	
	}
	
	/**
	 * logTag for logging purposes
	 */
	private static final String _logTag = "com.smartmail.utility";
}
